/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

************************************************************************************************/
using System;
using System.Collections.Specialized;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Votations.NSurvey.Data;
using Votations.NSurvey.BusinessRules;
using Votations.NSurvey.DataAccess;
using Votations.NSurvey.Resources;
using Microsoft.VisualBasic;


namespace Votations.NSurvey.Security
{

	/// <summary>
	/// Add in that handles the ASP.net security 
	/// context (forms, windows, custom ...) to detect if a 
	/// user is logged in and retrieve the username from the aspnet context
	/// </summary>
	public class DNNSecurityAddIn : IWebSecurityAddIn
	{
		public event UserAuthenticatedEventHandler UserAuthenticated;

		public int SurveyId 
		{
			get { return _surveyId; }
			set { _surveyId = value; }
		}

		public int AddInDbId 
		{
			get { return _addInDbId; }
			set { _addInDbId = value; }
		}

		public int Order
		{
			get { return _order; }
			set { _order = value; }
		}

		public string Description
		{
			get { return _description; }
			set { _description = value; }
		}

		public bool Disabled
		{
			get { return _disabled; }
			set { _disabled = value; }
		}

		public StateBag ViewState
		{
			get { return _viewState; }
			set { _viewState = value; }
		}

		/// <summary>
		/// Check if the current user has given
		/// the correct credentials
		/// </summary>
		public bool IsAuthenticated()
		{
			bool isAuth = false;

// Code to check if the DNN User has already voted or not and can take the survey

			if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
			{
				int iUserId =  int.Parse(HttpContext.Current.User.Identity.Name);
				DotNetNuke.UserController uc = new DotNetNuke.UserController();
				DotNetNuke.UserInfo ui = uc.GetUser(WebAdmin.Helpers.NukeHelper.PortalSettings.PortalId, iUserId);
				if ((ui.Username.Length > 0 &&
					!new Voters().HasUserNameVoted(SurveyId, ui.Username)) ||
					new Surveys().AspSecurityAllowsMultipleSubmissions(SurveyId))
				{
					isAuth = true;
				}
			}

			return isAuth;
		}

		/// <summary>
		/// Must create and return the control 
		/// that will show the logon interface.
		/// If none is available returns null
		/// </summary>
		public Control GetLoginInterface(Style controlStyle)
		{
			return null;
		}

		/// <summary>
		/// Must create and return the control 
		/// that will show the administration interface
		/// If none is available returns null
		/// </summary>
		public Control GetAdministrationInterface(Style controlStyle)
		{
	
			_adminTable = new Table();
			_adminTable.ControlStyle.CopyFrom(controlStyle);
			_adminTable.Width = Unit.Pixel(700);
			TableCell adminCell = new TableCell();
			TableRow adminRow = new TableRow();
			adminCell.ColumnSpan = 2;
			adminCell.Text ="This is a DNN security addin";
			adminRow.Cells.Add(adminCell);
			_adminTable.Rows.Add(adminRow);

			adminCell = new TableCell();
			adminRow = new TableRow();
			CheckBox multipleSubmissionsCheckBox = new CheckBox();
			multipleSubmissionsCheckBox.Checked = new Surveys().AspSecurityAllowsMultipleSubmissions(SurveyId);;
			Label multipleSubmissionsLabel = new Label();

			multipleSubmissionsLabel.ControlStyle.Font.Bold = true;
			multipleSubmissionsLabel.Text = "Accept multiple submission";
			adminCell.Width = Unit.Pixel(200);
			adminCell.Controls.Add(multipleSubmissionsLabel);
			adminRow.Cells.Add(adminCell);
			adminCell = new TableCell();
			multipleSubmissionsCheckBox.CheckedChanged += new EventHandler(OnCheckBoxChange);
			multipleSubmissionsCheckBox.AutoPostBack = true;
			adminCell.Controls.Add(multipleSubmissionsCheckBox);
			adminCell.Width = Unit.Pixel(500);
			adminRow.Cells.Add(adminCell);
			_adminTable.Rows.Add(adminRow);
			
			return _adminTable;
		}
		
		protected virtual void OnCheckBoxChange(Object sender, EventArgs e)
		{
		/// Update the custom config table of the database could be 
		/// vts_DNNSecurityAddInConfig(SurveyId int, MultipleSubmission bit) 
		
		new Survey().UpdateAspSecuritySettings(SurveyId, ((CheckBox)sender).Checked);
		}

		/// <summary>
		/// Method called once an addin has been added to a survey
		/// Can be used to set default values, settings for the addin
		/// </summary>
		public void InitOnSurveyAddition()
		{
		}

		/// <summary>
		/// Method called once an addin has been remove from a survey
		/// Can be used to remove useless settings for the addin
		/// </summary>
		public void UnInitOnSurveyRemoval()
		{
		}


		/// <summary>
		/// Method to handle voter data once it has been stored in the database
		/// </summary>
		/// <param name="voter">Voter information as saved in the database and its answers</param>
		public void ProcessVoterData(VoterAnswersData voter)
		{
//			Store DNN UserName along with the voterid in a custom table 
//			best would be: vts_tbDNNUser (VoterId, UserName, DNNUserID) 
//			DNNUserID is useful so we can directly check the user id in the 
//			isauthenticated method
//			Get the ID from HttpContext.Current.User.Identity.Name and associated the UserName 

			int voterId = voter.Voters[0].VoterId;
		}

		/// <summary>
		/// Can return keys/values of the custom 
		/// stored data during the ProcessVoterData. 
		/// At this time these data are retrieved to
		/// be shown in individual reports and for results export
		/// </summary>
		public NameValueCollection GetAddInVoterData(int voterId)
		{
//			Get DNN UserName that was used with the voterid from database
//			NameValueCollection myData = new NameValueCollection();
//			myData.Add("userid", youruseridentity);
//			return myData;
		}

		StateBag _viewState;

		Table _adminTable;
		int _surveyId,
			_order,
			_addInDbId;
		string _description;
		bool _disabled;
	}
}
